package com.doublefish.doublefishrobot.utils.db.database;

import android.content.Context;
import android.util.Log;

import com.doublefish.doublefishrobot.utils.db.database.bean.SQLiteResult;
import com.doublefish.doublefishrobot.utils.db.database.bean.SqlInfoModel;
import com.doublefish.doublefishrobot.utils.db.database.bean.TableInfoModel;

import net.sqlcipher.database.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 作者:dugaofeng on 2024/10/16 14:36
 */
public class SQLiteDatabaseManager {

    private boolean didCreatDataBase = false;  //是否已经初始化了数据库
    SQLiteDatabaseHelper sqLiteDatabaseHelper = null;

    private TableInfoModel tableInfoModel; //所有表的字段信息

    private static SQLiteDatabaseManager instance;
    private SQLiteDatabaseManager() {
        tableInfoModel = new TableInfoModel();
    }

    public static SQLiteDatabaseManager getInstance() {
        if (instance == null) {
            synchronized (SQLiteDatabaseManager.class) {
                if (instance == null) {
                    instance = new SQLiteDatabaseManager();
                }
            }
        }
        return instance;
    }

    public boolean isDidCreatDataBase() {
        return didCreatDataBase;
    }

    //初始化 数据库 和 表
    public boolean creatDataBaseTables(Context context, String dbName,String dbPwd, int version, List<SqlInfoModel> sqlInfoModels) {
        try {
            if (!didCreatDataBase) {
                SQLiteDatabase.loadLibs(context); // 加载数据库的三方库
                //初始化数据库 创建表
                sqLiteDatabaseHelper = new SQLiteDatabaseHelper(context, dbName, dbPwd, version, sqlInfoModels);

                //获取当前存在的所有数据表的表名
                List<String> tableNames = getAllExistTables(sqlInfoModels, version);
                //获取表结构
                for (String tableName:tableNames) {
                    Map<String,Integer> fields = sqLiteDatabaseHelper.getFieldsOfTable(tableName);
                    tableInfoModel.saveFieldsOfTable(tableName,fields);
                }

                didCreatDataBase = true;
            }
        } catch (Exception ex) {
            Log.e("SQLiteDatabaseManager", "loadSqlcipherLibs " + ex.getMessage());
        }
        return didCreatDataBase;
    }

    // 关闭数据库
    public void closeDatabase() {
        if (sqLiteDatabaseHelper == null)
            return;
        sqLiteDatabaseHelper.close();
    }

    public TableInfoModel getTableInfoModel() {
        return tableInfoModel;
    }

    /****** 数据库的增删改查 ********/

    /**
     * 数据库的插入
     * @param sql  要执行的sql语句
     * @return
     */
    public SQLiteResult insertData(String sql) {
        if (sql == null || "".equals(sql.trim()))
            return SQLiteResult.SqlSentenceError();

        if (sqLiteDatabaseHelper == null)
            return SQLiteResult.SqLiteDatabaseHelperIsNull();

        return sqLiteDatabaseHelper.execSql(sql);
    }

    /**
     * 数据库的插入
     * @param tableName
     * @param data
     * @return
     */
    public SQLiteResult insertData(String tableName, Map<String,Object> data) {
        if (tableName == null || "".equals(tableName))
            return  SQLiteResult.TableNameError();

        if (data == null)
            return SQLiteResult.SqlInsertDataIsNull();

        if (sqLiteDatabaseHelper == null)
            return SQLiteResult.SqLiteDatabaseHelperIsNull();

        if (!sqLiteDatabaseHelper.isExistTable(tableName))
            return SQLiteResult.TableNameError();

        //构造sql语句
        String sql = SQLiteSentenceMakeHelper.makeInsertSql(tableName,tableInfoModel,data);
        //执行sql语句
        return sqLiteDatabaseHelper.execSql(sql);
    }


    /**
     * 数据库的插入
     * @param tableName
     * @param list
     * @return
     */
    public SQLiteResult insertData(String tableName, List<Map<String,Object>> list) {
        if (tableName == null || "".equals(tableName))
            return  SQLiteResult.TableNameError();

        if (list == null || list.size() == 0)
            return SQLiteResult.SqlInsertDataIsNull();

        if (sqLiteDatabaseHelper == null)
            return SQLiteResult.SqLiteDatabaseHelperIsNull();

        if (!sqLiteDatabaseHelper.isExistTable(tableName))
            return SQLiteResult.TableNameError();

        //构造sql语句
        List<String> sqlList = SQLiteSentenceMakeHelper.makeInsertSql(tableName,tableInfoModel,list);

        try {
            sqLiteDatabaseHelper.beginTransaction();

            for (String sql: sqlList) {
                SQLiteResult result = sqLiteDatabaseHelper.execSql(sql);
                if (!result.isSuccess()) { //有错误直接返回
                    return result;
                }
            }
            sqLiteDatabaseHelper.setTransactionSuccessful();

            return SQLiteResult.SqlExecuteSuccess();
        } catch (Exception e) {
            Log.e("SQLiteDatabaseManager","insertData " + e.getMessage());
            return new SQLiteResult(false,e.getMessage());
        } finally {
            sqLiteDatabaseHelper.endTransaction();
        }
    }

    /**
     * 数据库的删除
     * @param sql  要执行的sql语句
     * @return
     */
    public SQLiteResult deleteData(String sql) {
        if (sql == null || "".equals(sql.trim()))
            return SQLiteResult.SqlSentenceError();

        if (sqLiteDatabaseHelper == null)
            return SQLiteResult.SqLiteDatabaseHelperIsNull();

        return sqLiteDatabaseHelper.execSql(sql);
    }

    /**
     * 数据库的删除
     * @param tableName 要删除数据的表
     * @param data  删除数据的条件
     * @return
     */
    public SQLiteResult deleteData(String tableName, Map<String,Object> data) {
        if (tableName == null || "".equals(tableName))
            return SQLiteResult.TableNameError();

        if (sqLiteDatabaseHelper == null)
            return SQLiteResult.SqLiteDatabaseHelperIsNull();

        if (!sqLiteDatabaseHelper.isExistTable(tableName))
            return SQLiteResult.TableNameError();

        //构造sql语句
        String sql = SQLiteSentenceMakeHelper.makeDeleteSql(tableName,tableInfoModel,data);
        //执行sql语句
        return sqLiteDatabaseHelper.execSql(sql);
    }


    /**
     * 执行sql语句查询 count
     * @param tableName  表名
     * @param data       查询条件
     * @return
     */
    public SQLiteResult queryCount(String tableName, Map<String, Object> data) {
        if (tableName == null || "".equals(tableName))
            return SQLiteResult.TableNameError();

        if (sqLiteDatabaseHelper == null)
            return SQLiteResult.SqLiteDatabaseHelperIsNull();

        if (!sqLiteDatabaseHelper.isExistTable(tableName))
            return SQLiteResult.TableNameError();

        //生成sql语句
        String sql = SQLiteSentenceMakeHelper.makeQueryCountSql(tableName, tableInfoModel, data);
        //执行sql语句
        return sqLiteDatabaseHelper.queryCount(sql);
    }


    /**
     * 执行sql语句查询 count
     * @param sql  sql语句
     * @return
     */
    public SQLiteResult queryCount(String sql) {
        if (sql == null || "".equals(sql.trim()))
            return SQLiteResult.SqlSentenceError();

        if (sqLiteDatabaseHelper == null)
            return SQLiteResult.SqLiteDatabaseHelperIsNull();

        //执行sql语句
        return sqLiteDatabaseHelper.queryCount(sql);
    }

    /**
     * 查找数据
     * @param sql 查找的sql
     * @return
     */
    public SQLiteResult queryData(String sql) {
        if (sql == null || "".equals(sql.trim()))
            return SQLiteResult.SqlSentenceError();
        if (sqLiteDatabaseHelper == null)
            return SQLiteResult.SqLiteDatabaseHelperIsNull();

        //执行sql语句
        return sqLiteDatabaseHelper.queryData(sql);
    }


    /**
     * 查找数据
     * @param data 查找的条件
     * @return
     */
    public SQLiteResult queryData(String tableName, Map<String,Object> data) {
        if (tableName == null || "".equals(tableName))
            return SQLiteResult.TableNameError();
        if (sqLiteDatabaseHelper == null)
            return SQLiteResult.SqLiteDatabaseHelperIsNull();

        if (!sqLiteDatabaseHelper.isExistTable(tableName))
            return SQLiteResult.TableNameError();

        //生成sql语句
        String sql = SQLiteSentenceMakeHelper.makeQuerySql(tableName, tableInfoModel, data);
        //执行sql语句
        return sqLiteDatabaseHelper.queryData(sql);
    }

    /**
     * 执行更新的sql语句
     * @param sql   更新的sql语句
     * @return
     */
    public SQLiteResult updateData(String sql) {
        if (sql == null || "".equals(sql.trim()))
            return SQLiteResult.SqlSentenceError();

        if (sqLiteDatabaseHelper == null)
            return SQLiteResult.SqLiteDatabaseHelperIsNull();

        //执行sql语句
        return sqLiteDatabaseHelper.execSql(sql);
    }

    /**
     * 执行更新的sql语句
     * @param tableName 表名
     * @param data      要更新的数据
     * @param whereData 更新的条件
     * @return
     */
    public SQLiteResult updataData(String tableName, Map<String,Object> data, Map<String,Object> whereData) {
        if (tableName == null || "".equals(tableName))
            return SQLiteResult.TableNameError();

        if (sqLiteDatabaseHelper == null)
            return SQLiteResult.SqLiteDatabaseHelperIsNull();

        if (!sqLiteDatabaseHelper.isExistTable(tableName))
            return SQLiteResult.TableNameError();

        //生成sql语句
        String sql = SQLiteSentenceMakeHelper.makeUpdateSql(tableName, tableInfoModel, data, whereData);
        //执行sql语句
        return sqLiteDatabaseHelper.execSql(sql);
    }

    /******************************/


    /**
     * 获取当前存在的所有数据表的表名
     * @param sqlInfoModels  所有的sql语句
     * @return  表名
     */
    private List<String>  getAllExistTables(List<SqlInfoModel> sqlInfoModels, int dbVersion) {
        List<String> tableNames = new ArrayList<>();

        if (sqlInfoModels == null || sqlInfoModels.size() == 0) {
            return tableNames;
        }

        for (SqlInfoModel sqlInfoModel:sqlInfoModels) {
            if (sqlInfoModel.getVersion() <= dbVersion) {   //sql语句的版本必须小于当前版本
                SqlInfoModel.SqlOperateType sqlOperateType = sqlInfoModel.getOperateType();
                String tableName = sqlInfoModel.getTableName();

                switch (sqlOperateType) {
                    case ADD_TABLE:
                        //新增表
                        tableNames.add(tableName);
                        break;
                    case DELETE_TABLE:
                        //删除表
                        tableNames.remove(tableName);
                        break;
                    case ALTER_TABLENAME:
                        //修改表名
                        tableNames.remove(sqlInfoModel.getOldTableName());  //去掉就表名
                        tableNames.add(tableName);            //添加新表名
                        break;
                    case UPDATE_TABLE:
                        break;
                }
            }
        }

        return tableNames;
    }


    /******** 事物 **********/
    public void beginTransaction(){
        if (sqLiteDatabaseHelper == null)
            return;
        sqLiteDatabaseHelper.beginTransaction();
    }

    public void setTransactionSuccessful() {
        if (sqLiteDatabaseHelper == null)
            return;
        sqLiteDatabaseHelper.setTransactionSuccessful();
    }

    public void endTransaction() {
        if (sqLiteDatabaseHelper == null)
            return;
        sqLiteDatabaseHelper.endTransaction();
    }

}
